package cn.zz.camerasdk.filter.util;

/**
 * author: zhu on 2017/7/7 17:16
 * email: mackkill@gmail.com
 */


import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.os.Build.VERSION;
import android.text.ClipboardManager;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import static android.content.Context.CLIPBOARD_SERVICE;
import static android.content.Context.INPUT_METHOD_SERVICE;

public class ImageFilterUtil {
    public static int type_photo = 0;
    public static int type_voice = 1;
    public static int type_temp = 2;

    public ImageFilterUtil() {
    }

    public static void deleteDBs(String path) {
        File db = new File(path);
        deleteFileOrDirectory(db);
    }

    public static void deleteFileOrDirectory(File file) {
        try {
            deleteSubFiles(file);
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    public static void deleteSubFiles(File file) {
        try {
            if(!file.exists()) {
                return;
            }

            String e = file.getAbsolutePath();
            if(file.isFile()) {
                file.delete();
            } else if(file.isDirectory()) {
                String[] tempList = file.list();
                File temp = null;

                for(int i = 0; i < tempList.length; ++i) {
                    if(e.endsWith(File.separator)) {
                        temp = new File(e + tempList[i]);
                    } else {
                        temp = new File(e + File.separator + tempList[i]);
                    }

                    if(temp.isFile()) {
                        temp.delete();
                    }

                    if(temp.isDirectory()) {
                        deleteSubFiles(new File(e + "/" + tempList[i]));
                    }
                }
            }
        } catch (Exception var5) {
            var5.printStackTrace();
        }

    }

    public static boolean copyFile(String oldPath, String newPath) {
        try {
            File e = new File(oldPath);
            boolean byteread = false;
            if(!e.exists()) {
                return false;
            } else {
                FileInputStream inStream = new FileInputStream(oldPath);
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[4096];

                int byteread1;
                while((byteread1 = inStream.read(buffer)) != -1) {
                    fs.write(buffer, 0, byteread1);
                }

                inStream.close();
                fs.close();
                return true;
            }
        } catch (Exception var7) {
            var7.printStackTrace();
            return false;
        }
    }

    public static int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dpValue * scale + 0.5F);
    }

    public static int px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue / scale + 0.5F);
    }

    public static int getscreenwidth(Context context) {
        DisplayMetrics dm2 = context.getResources().getDisplayMetrics();
        return dm2.widthPixels;
    }

    public static int getscreenheight(Context context) {
        DisplayMetrics dm2 = context.getResources().getDisplayMetrics();
        return dm2.heightPixels;
    }

    public static int getStatusBarHeight() {
        return Resources.getSystem().getDimensionPixelSize(Resources.getSystem().getIdentifier("status_bar_height", "dimen", "android"));
    }

    public static Bitmap decodeFile(File f, int REQUIRED_SIZE) {
        try {
            Options e = new Options();
            e.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), (Rect)null, e);
            int width_tmp = e.outWidth;
            int height_tmp = e.outHeight;

            int scale;
            for(scale = 1; width_tmp / 2 >= REQUIRED_SIZE && height_tmp / 2 >= REQUIRED_SIZE; scale *= 2) {
                width_tmp /= 2;
                height_tmp /= 2;
            }

            if(width_tmp > 1000) {
                width_tmp = e.outWidth;

                for(scale = 2; width_tmp / scale > 1000; ++scale) {
                    ;
                }
            }

            Options o2 = new Options();
            o2.inSampleSize = scale;

            try {
                FileInputStream err = new FileInputStream(f);
                return BitmapFactory.decodeStream(err, (Rect)null, o2);
            } catch (OutOfMemoryError var8) {
                var8.printStackTrace();
            }
        } catch (Exception var9) {
            var9.printStackTrace();
        }

        return null;
    }

    public static Bitmap decodeImage(Bitmap bitmap, int REQUIRED_SIZE) {
        try {
            int e = bitmap.getWidth();
            int height_tmp = bitmap.getHeight();
            int tmp = e > height_tmp?height_tmp:e;
            Matrix matrix = new Matrix();
            if(tmp > REQUIRED_SIZE) {
                float scale = (float)REQUIRED_SIZE / (float)tmp;
                matrix.postScale(scale, scale);
            } else {
                matrix.postScale(1.0F, 1.0F);
            }

            return Bitmap.createBitmap(bitmap, 0, 0, e, height_tmp, matrix, true);
        } catch (Exception var7) {
            var7.printStackTrace();
            return null;
        }
    }

    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException var7) {
            throw new RuntimeException("Huh, MD5 should be supported?", var7);
        } catch (UnsupportedEncodingException var8) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", var8);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        byte[] var6 = hash;
        int var5 = hash.length;

        for(int var4 = 0; var4 < var5; ++var4) {
            byte b = var6[var4];
            if((b & 255) < 16) {
                hex.append("0");
            }

            hex.append(Integer.toHexString(b & 255));
        }

        return hex.toString();
    }

    public static Bitmap getImage(Context context, String path, int size) {
        Bitmap bitmap = null;

        try {
            boolean e = false;
            ExifInterface exif = new ExifInterface(path);
            short e1;
            switch(exif.getAttributeInt("Orientation", 0)) {
                case 3:
                    e1 = 180;
                    break;
                case 4:
                case 5:
                case 7:
                default:
                    e1 = 0;
                    break;
                case 6:
                    e1 = 90;
                    break;
                case 8:
                    e1 = 270;
            }

            bitmap = decodeFile(new File(path), size);
            if(e1 != 0) {
                Matrix m = new Matrix();
                int width = bitmap.getWidth();
                int height = bitmap.getHeight();
                m.setRotate((float)e1);
                bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, m, true);
            }
        } catch (Exception var9) {
            var9.printStackTrace();
        }

        return bitmap;
    }

    public static SpannableStringBuilder gettextstyle(String str, String key, int color) {
        int index = str.toUpperCase().indexOf(key.toUpperCase());
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        if(index != -1) {
            style.setSpan(new ForegroundColorSpan(color), index, index + key.length(), 34);
        }

        return style;
    }

    public static SpannableStringBuilder gettextstyle(SpannableString str, String key, int color) {
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        style.setSpan(new ForegroundColorSpan(color), 0, key.length(), 34);
        return style;
    }

    public static SpannableStringBuilder gettextstylefromend(SpannableString str, String key, int color) {
        SpannableStringBuilder style = new SpannableStringBuilder(str);
        style.setSpan(new ForegroundColorSpan(color), str.length() - key.length(), str.length(), 34);
        return style;
    }

    public static String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];

        int n;
        while((n = in.read(b)) != -1) {
            out.append(new String(b, 0, n));
        }

        return out.toString();
    }

    public static String getCurDateforFileName() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    public static String getCurDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    public static String getCurDay() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    public static String getCurDatetoMd5() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        return md5(formatter.format(curDate));
    }

    public static String getDate(long milliseconds) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(milliseconds);
        return formatter.format(curDate);
    }

    public static void openKeyboard(Context mContext) {
        ((InputMethodManager)mContext.getSystemService(INPUT_METHOD_SERVICE)).toggleSoftInput(0, 2);
    }

    public static void closeKeyboard(Activity ac) {
        if(ac != null) {
            InputMethodManager imm = (InputMethodManager)ac.getSystemService(INPUT_METHOD_SERVICE);
            if(ac.getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(ac.getCurrentFocus().getWindowToken(), 2);
            }

        }
    }

    public static String twoDateDistance(String startTime) {
        String result = "";
        Date startDate = null;
        if(startTime != null && startTime.trim().length() != 0) {
            try {
                startDate = ConverToDate(startTime);
                Date e = new Date(System.currentTimeMillis());
                long timeLong = e.getTime() - startDate.getTime();
                long oneMin = 60000L;
                long oneHour = 3600000L;
                long oneDay = 86400000L;
                long oneMonth = 2592000000L;
                long oneYear = 31104000000L;
                if(timeLong < oneMin) {
                    result = "刚刚";
                } else if(timeLong < oneHour && timeLong >= oneMin) {
                    timeLong /= oneMin;
                    result = timeLong + "分钟前";
                } else if(timeLong < oneDay && timeLong >= oneHour) {
                    timeLong /= oneHour;
                    result = timeLong + "小时前";
                } else if(timeLong < oneMonth && timeLong >= oneDay) {
                    timeLong /= oneDay;
                    result = timeLong + "天前";
                } else if(timeLong < oneYear && timeLong >= oneMonth) {
                    timeLong /= oneMonth;
                    result = timeLong + "月前";
                } else {
                    timeLong /= oneYear;
                    result = timeLong + "年前";
                }
            } catch (Exception var16) {
                var16.printStackTrace();
            }

            return result;
        } else {
            return result;
        }
    }

    public static String msgDatefromNow(String startTime) {
        String result = "";
        Date startDate = null;
        if(startTime != null && startTime.trim().length() != 0) {
            try {
                startDate = ConverToDate(startTime);
                Date e = new Date(System.currentTimeMillis());
                long timeLong = e.getTime() - startDate.getTime();
                if(timeLong < 60000L) {
                    result = "刚刚";
                } else if(timeLong < 1800000L) {
                    timeLong = timeLong / 1000L / 60L;
                    result = timeLong + "分钟前";
                } else {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
                    result = sdf.format(startDate);
                }
            } catch (Exception var7) {
                var7.printStackTrace();
            }

            return result;
        } else {
            return result;
        }
    }

    public static boolean isDateOverNow(String time) {
        Date startDate = null;
        if(time != null && time.trim().length() != 0) {
            try {
                startDate = ConverToDate(time + " 00:00:00");
                Date e = new Date(System.currentTimeMillis());
                long timeLong = e.getTime() - startDate.getTime();
                return timeLong < 0L;
            } catch (Exception var5) {
                var5.printStackTrace();
                return true;
            }
        } else {
            return true;
        }
    }

    public static boolean twoDateDistance(String startTime, String endTime) {
        boolean result = false;

        try {
            Date e = ConverToDate(startTime);
            Date endDate = ConverToDate(endTime);
            long timeLong = endDate.getTime() - e.getTime();
            if(Math.abs(timeLong) < 180000L) {
                result = true;
            }
        } catch (Exception var7) {
            var7.printStackTrace();
        }

        return result;
    }

    public static boolean isTimeNew(String curTime, String mTime) {
        boolean result = false;

        try {
            Date e = ConverToDate(curTime);
            Date mDate = ConverToDate(mTime);
            result = e.getTime() - mDate.getTime() > 0L;
        } catch (Exception var5) {
            var5.printStackTrace();
        }

        return result;
    }

    public static Date ConverToDate(String strDate) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.parse(strDate);
    }

    public static void clipText(Context context, String text) {
        if(VERSION.SDK_INT < 11) {
            ClipboardManager mClipboard = (ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE);
            mClipboard.setText(text);
        } else {
            android.content.ClipboardManager mClipboard1 = (android.content.ClipboardManager)context.getSystemService(CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("simple text", text);
            mClipboard1.setPrimaryClip(clip);
        }

        Toast.makeText(context, "已复制", Toast.LENGTH_SHORT).show();
    }

    public static void updateMedia(Context context, String filepath) {
        MediaScannerConnection.scanFile(context, new String[]{filepath}, (String[])null, (OnScanCompletedListener)null);
    }

    public static BitmapDrawable getDrawable(Context context, int resource_Id) {
        Options opt = new Options();
        opt.inPreferredConfig = Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        InputStream is = context.getResources().openRawResource(resource_Id);
        Bitmap bm = BitmapFactory.decodeStream(is, (Rect)null, opt);
        return new BitmapDrawable(context.getResources(), bm);
    }
}
